<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8" />
    <title>聊天</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>

<style>
    body {
        font-family: Arial, sans-serif;
        /* 设置字体 */
        display: flex;
        justify-content: center;
        align-items: center;
        min-height: 100vh;
        background-image: url("background/background-chat.png");
        background-repeat:no-repeat;
        background-position:center center;
        background-attachment:fixed;
        background-size:cover;
    }

    .container {
        position: relative;
        width: 1200px;
        max-width: 100%;
        height: 800px;
        background-color: rgb(198, 255, 179,0.28);
        display: flex;
    }

    /*左状态边框*/
    .left-box{
        position: relative;
        flex:6%;
        background-image: linear-gradient(to bottom, #40fff8, rgba(10, 246, 22, 0.3));
    }
    /*头像设置*/
    .img-left{
        margin: 5px;
        width: 70px;
        height: 70px;
        border-radius: 10%;
    }
    /*退出键*/
    .img-logout{
        position: absolute;
        bottom: 10px; /* 定位到容器底部 */
        left: 50%; /* 居中对齐 */
        transform: translateX(-50%); /* 水平居中 */
        width: 50px;
        height: 50px;
        cursor: pointer;
    }

    /*聊天边框*/
    .chat-box {
        border: 1px solid #ccc;
        /* 设置边框 */
        background-color: #ffffff;
        position: relative;
        background-repeat:no-repeat;
        flex: 79%;
        opacity: 0.5;
    }

    .message-sent {
        background-color: #0080ff;
        color: white;
        float: right;
        max-width: 60%;
        text-align: right;
        border-radius: 8px;
        padding: 10px;
        margin-right: 10px;
        margin-left: auto;
        margin-bottom: 15px;
    }

    .message-receive {
        background-color: #b6ff7d;
        color: #000000;
        float: left;
        max-width: 60%;
        text-align: left;
        border-radius: 8px;
        padding: 10px;
        margin-right: auto;
        margin-left: 10px;
        margin-bottom: 15px;
    }
    /* 全局样式 */
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    /* 聊天框样式 */
    #content {
        position: relative;
        width: 100%;
        height: 65%;
        padding: 50px;
        overflow-y: auto;
        display: flex;
        flex-direction: column;
        overflow-y: scroll;


    }
    #content::-webkit-scrollbar
    {
        display: none;
    }

    .message img {
        max-width: 100%;
        max-height: 200px;
        display: block;
    }

    .leftside {
        position: relative;
        flex: 15%;
        background: rgb(255, 255, 255,0.4);
        border-right: 1px solid rgba(0, 0, 0, 0.2);
    }

    .leftside1 {
        position: relative;
        width: 100%;
        height: 42%;
        background: rgb(255, 255, 255,0.4);
        display: flex;
    }

    #input_text {
        flex: 1;
        /* 输入框占满剩余的空间 */
        margin-bottom: 10px;
    }

    /* 在线好友列表样式 */
    #hylist {
        height: 48%;
        overflow-y: auto;
        padding: 10px;
        /* border: 1px solid #ccc; */
        border-radius: 5px;
    }

    #hylist li {
        margin-bottom: 10px;
        cursor: pointer;
    }

    /* 系统广播样式 */
    #lslist {
        height: 80%;
        overflow-y: auto;
        padding: 10px;
        /* border: 1px solid #ccc; */
        border-radius: 5px;
    }

    #lslist li {
        margin-bottom: 10px;
    }
    #lslist::-webkit-scrollbar {
        display: none;
    }

    #inputbox {
        position: relative;
        width: 100%;
        height: 20%;
        background: #ffffff;
        display: flex;
        justify-content: space-between;
        /* align-items: center; */
        padding: 0 15px;
    }

    #header12 {
        position: relative;
        width: 100%;
        height: 8%;
        background-image: linear-gradient(to right, #40fff8, rgb(182, 255, 125));
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 15px;
    }
    #header13 {
        position: relative;
        width: 100%;
        height: 6%;
        background: rgba(43, 255, 247, 0.45);
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 15px;
    }

    #header {
        position: relative;
        width: 100%;
        height: 8%;
        background: rgb(182, 255, 125);
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 15px;
    }

    #header1 {
        position: relative;
        width: 100%;
        height: 7%;
        background: rgb(162, 238, 123);
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 15px;
    }


    /*表情照片图标分布*/
    .aui-info {
        position: relative;
        padding-right: 10px;
    }

    .fileInput {
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        opacity: 0;
        display: block;
        width: 3.5rem;
        clear: both;
        display: block;
        margin: auto;
        background-color: red;
    }
    .filetc {
        position: relative;
        width: 85%;
        height: 7%;
        background: rgb(162, 238, 123);
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 15px;
    }
    /* 设置输入框的宽度和高度 */
    textarea {
        width: 90%;
        height: 100%;
        /* 设置输入框的高度为50像素 */
        background-color: white;
        padding: 0;
        margin: 0 -15px;
        border-radius: 4px;
        box-sizing: border-box;
        font-size: 16px;
    }

    .button {
        width: 10%;
        background-color: #4caf50;
        border: none;
        color: white;
        padding: 10px 20px;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
        margin: 0 -15px;
        cursor: pointer;
        border-radius: 5px;
    }


    #emoji-button {
        background: none;
        border: none;
        z-index: 9999;
    }

    #emoji-button img {
        width: 3rem;
    }

    .emoji {
        position: relative;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 2rem;
        cursor: pointer;
        transition: transform 0.2s ease;
        height: 3rem;
        width: 3rem;
        margin: 0.2rem 0.1rem; /* 把表情之间的间距缩小 */
    }

    .emoji:hover {
        transform: scale(1.2);
    }

    .emoji::before {
        content: '';
        position: absolute;
        top: -0.5rem;
        right: -0.5rem;
        bottom: -0.5rem;
        left: -0.5rem;
        border: 1px solid #fff;
        border-radius: 0.3rem;
        opacity: 0;
        transition: opacity 0.2s ease;
    }

    .emoji:hover::before {
        opacity: 1;
    }

    #emoji-container {
        position: absolute;
        top: 2rem;
        left: 0;
        right: 0;
        margin: auto;
        border: 1px solid #ccc;
        padding: 0.5rem;
        z-index: 9999;
        min-height: 6rem; /* 最小高度，确保 emoji picker 容器不会收缩过小 */
        min-width: 31rem;
    }

    .emoji-picker {
        display: grid;
        grid-template-columns: repeat(7, 1fr);
        /*grid-auto-rows: 6rem;*/
        grid-gap: 0.4rem; /* 可以改成 grid-gap */
        max-height: 10rem;
        overflow: auto;
        -ms-overflow-style: none;
        scrollbar-width: none;
        width: 30rem;
    }

    .emoji-picker::-webkit-scrollbar {
        display: none;
    }

    .friend-link {
        display: inline-block;
        padding: 5px 60px;
        font-size: 16px;
        text-align: center;
        color: #949494;
        background: linear-gradient(to right, rgba(43, 255, 247, 0.45), rgb(182, 255, 125));
        border: 2px solid rgba(32, 238, 238, 0.3);
        border-radius: 10px;
        text-decoration: none;
        margin-bottom: 10px;
        transition: all 0.3s ease-in-out;
    }

    .friend-link:hover {
        background: transparent;
        color: #7fe783;
        border-color: rgba(32, 238, 238, 0.3);
    }
    #link-button{
        position: absolute;
        text-align: center;
        align-items: center; /* 垂直居中 */
        justify-content: center; /* 水平居中 */
        text-decoration: none;
        display:flex;
        border: none;
        font-size: 16px;
        margin: 0;
        height:70%;
        width:10%;
        top: 5px;
        right: 5px;
        background-color: #14ff20;
        color: #7e6868;
        cursor: pointer;
        border-radius: 5px;
    }
</style>

<body>
<div class="container">

    <div class="left-box">
        <img class="img-left" id="avatarImg" src="">
        <h4 style="text-align: center; font-family: SimSun,serif" id="username"></h4>
        <img class="img-logout" src="icon/退出.png" id="logout">
    </div>
    <div class="leftside">
        <div id="header12">在线好友</div>
        <div class="leftside1">
            <div id="hylist"></div>
        </div>

        <div id="header13">历史记录</div>

        <div class="leftside1">
            <div id="lslist"></div>
        </div>
    </div>
    <div class="chat-box">
        <div id="header">
            <h4 style="font-family:宋体,serif;text-align:center" id="new"></h4>
            <div id="link-button">下线</div>
        </div>
        <div id="content"></div>
        <div id="header1">
            <div class="aui-info">
                <img src="icon/图片.png" id="img" style="width: 3rem" />
                <input
                        type="file"
                        accept="image/*"
                        id="file"
                        name="file"
                        onchange="upload('#file', '#img');"
                        class="fileInput"
                        value=""
                />
            </div>
            <div class="aui-info">
                <button id="emoji-button">
                    <img src="icon/表情.png" style="width: 3rem;" />
                </button>
                <div id="emoji-container" style="display: none;">
                    <div class="emoji-picker">

                    </div>
                </div>
            </div>
            <div class="filetc"></div>
        </div>
        <div id="inputbox">
            <textarea name="text" id="input_text" style="resize: none" disabled></textarea>
            <button id="submit" class="button" disabled>发送</button>
        </div>
    </div>

</div>

<script>
    // // 页面加载时检查是否存在 session 数据
    // window.onload = function () {
    //     var sessionData = sessionStorage.getItem('key');
    //     if (sessionData != null) {
    //         // 如果存在 session 数据，则重新加载到 sessionStorage 中
    //         // 注意：这里假设 session 数据是以 JSON 格式存储的，
    //         // 如果您的数据格式不同，需要相应地更改代码。
    //         sessionStorage.setItem('key', JSON.stringify(sessionData));
    //     }
    // }

    // // 在页面关闭时保存 session 数据
    // window.onbeforeunload = function () {
    //
    // }
    document.styleSheets;
    var username;
    var avatar;
    var flag = 0;
    $(function () {
        var toName;
        $.ajax({
            url: "getUsername",
            success: function (res) {
                username = res;
                $("#username").html(username + "<br><span>在线</span>");
                // $("#username").html("用户：123<span>在线</span>");
            },
            async: false, //同步请求，只有上面好了才会接着下面
        });
        $.ajax({
            url: "getAvatar",
            data: {
                username: username
            },
            success: function (res) {
                avatar = res;
                console.log(avatar);
                $("#avatarImg").attr("src", "data:image/jpeg;base64," + avatar);

                // $("#username").html("用户：123<span>在线</span>");
            },
            async: false, //同步请求，只有上面好了才会接着下面
        });
        var historyListStr = "";
        $.ajax({
            url: "getHistory",
            data: {
                username: username
            },
            success: function (res) {
                var chatPeople = JSON.parse(res);
                console.log(chatPeople);
                var chatData = chatPeople;

                for (var i = 0; i < chatData.length; i++) {
                    historyListStr += "<a class='friend-link' onclick=\"showHistory('" + chatData[i] + "')\">" + chatData[i] + "</a><br>";
                }
                $("#lslist").html(historyListStr);
            },
            async: false, //同步请求，只有上面好了才会接着下面
        });



        var host = window.location.host;
        var ws = new WebSocket("ws://"+host+"/chat");
        ws.onopen = function (ev) {

            $("#username").html(username + "<br><span>在线</span>");



            // $("#avatarImg").src(atob(avatar));
        };





        //接受消息

        (ws.onmessage = function (ev) {
            console.log("来接收信息了");
            var datastr = ev.data;
            var res = JSON.parse(datastr);
            console.log(res);
            //判断是否是系统消息
            if(res.system){
                //好友列表
                //系统广播
                var flag0 = 0;
                var names = res.message;
                var userlistStr = "";
                for (var name of names){
                    if (name != username){
                        userlistStr += "<a class='friend-link' onclick=\"showChat('" + name + "')\">" + name + "</a><br>";
                        if(flag == 1) {
                            if(name == toName)flag0 = 1;
                        }
                        //historyListStr += "<p>"+ name +"上线了</p>";
                    }
                    if(flag == 1 && flag0 == 0){
                        $("#content").html("");
                        flag = 0;
                    }
                };
                $("#hylist").html(userlistStr);
                // $("#lslist").html(historyListStr);

            }else {
                console.log(res);
                if (res.code == 1) { // 文本消息
                    var str = "<div span class='message-receive'>" + res.message + "</span><br>";
                    if (toName == res.fromName) {
                        $("#content").append(str);
                    }

                    var chatData = JSON.parse(sessionStorage.getItem(res.fromName)) || []; // 获取 chatData，如果不存在则为一个空数组

                    chatData.push({ type: "text", data: str }); // 将 HTML 代码添加到 chatData 中

                    sessionStorage.setItem(res.fromName, JSON.stringify(chatData)); // 将 chatData 存储到 sessionStorage 中
                } else if (res.code == 2) { // 图片消息
                    var img = $("<img>", { src: res.message });
                    var messageDiv = $("<div>", { class: "message" }).append(img);
                    messageDiv.addClass("message-receive"); // 添加 CSS 类
                    $("#content").append(messageDiv);

                    var chatData = JSON.parse(sessionStorage.getItem(res.fromName)) || []; // 获取 chatData，如果不存在则为一个空数组

                    chatData.push({ type: "image", data: res.message }); // 将图片的 URL 存储在 chatData 中

                    sessionStorage.setItem(res.fromName, JSON.stringify(chatData)); // 将 chatData 存储到 sessionStorage 中
                }
            };
        },
            ws.onclose = function (ev) {
                $("#username").html(username +"<br><span>离线</span>");
            }
        )

        showChat = function(name){
            // alert("dsaad");
            flag = 1;
            let myButton = document.getElementById("submit");
            // myButton.disabled = true; // 禁用按钮
             myButton.disabled = false; // 启用按钮
            toName = name;
            let text = document.getElementById("input_text");
            text.disabled = false;
            //清空聊天区
            $("#content").html("");
            $("#new").html("当前正与"+toName+"聊天");
            console.log("username = " + username + " toname = " + toName);
            $.ajax({
                type: "GET",
                url: "/getRecord?senderName=" + username + "&receiverName=" + toName,

                success: function(data) {
                    // 处理成功返回的数据
                    // data是一个JSON字符串，需要使用JSON.parse()方法将其转换为对象
                    var chatHistory = JSON.parse(data);
                    console.log(chatHistory);
                    var chatData = chatHistory;
                    for (var i = 0; i < chatData.length; i++) {
                        var message = chatData[i];
                        console.log("message.sendername = " + username + " message.receivername = " + toName);                        if (message.code == 1) {
                            var messageDiv = $("<div>", { class: "message" }).html(message.context);
                            if(message.sendername == username && message.receivername == toName)
                                messageDiv.addClass("message-sent");
                            else if(message.receivername == username && message.sendername == toName)
                                messageDiv.addClass("message-receive");

                        } else if (message.code == 2) {
                            var img = $("<img>", {src: message.context});
                            var messageDiv = $("<div>", {class: "message"}).append(img);
                            if(message.sendername == username && message.receivername == toName)
                                messageDiv.addClass("message-sent");
                            else if(message.receivername == username && message.sendername == toName)
                                messageDiv.addClass("message-receive");

                        }

                        $("#content").append(messageDiv);
                    }
                },
                error: function(xhr, status, error) {
                    // 处理请求失败
                    console.log("Error: " + error);
                }
            });


            // var chatData = JSON.parse(sessionStorage.getItem(toName)) || []; // 获取 chatData，如果不存在则为一个空数组
        };


        showHistory = function(name){
            // alert("dsaad");
            let myButton = document.getElementById("submit");
            myButton.disabled = true; // 禁用按钮
            // myButton.disabled = false; // 启用按钮

            let text = document.getElementById("input_text");
            text.disabled = true;

            toName = name;
            //清空聊天区
            $("#content").html("");


            $.ajax({
                type: "GET",
                url: "/getRecord?senderName=" + username + "&receiverName=" + toName,

                success: function(data) {
                    // 处理成功返回的数据
                    // data是一个JSON字符串，需要使用JSON.parse()方法将其转换为对象
                    var chatHistory = JSON.parse(data);
                    console.log(chatHistory);
                    var chatData = chatHistory;
                    for (var i = 0; i < chatData.length; i++) {
                        var message = chatData[i];
                        console.log("message.sendername = " + username + " message.receivername = " + toName);                        if (message.code == 1) {
                            var messageDiv = $("<div>", { class: "message" }).html(message.context);
                            if(message.sendername == username && message.receivername == toName)
                                messageDiv.addClass("message-sent");
                            else if(message.receivername == username && message.sendername == toName)
                                messageDiv.addClass("message-receive");

                        } else if (message.code == 2) {
                            var img = $("<img>", {src: message.context});
                            var messageDiv = $("<div>", {class: "message"}).append(img);
                            if(message.sendername == username && message.receivername == toName)
                                messageDiv.addClass("message-sent");
                            else if(message.receivername == username && message.sendername == toName)
                                messageDiv.addClass("message-receive");

                        }

                        $("#content").append(messageDiv);
                    }
                },
                error: function(xhr, status, error) {
                    // 处理请求失败
                    console.log("Error: " + error);
                }
            });


            // var chatData = JSON.parse(sessionStorage.getItem(toName)) || []; // 获取 chatData，如果不存在则为一个空数组
        };

        //发送消息
        $("#submit").click(function () {
            //获取输入的内容
            var data = $("#input_text").val();
            if(data==""||null==data){
                alert("发送消息不能为空")
                return;
            }else {
                $("#input_text").val("");
                var json = {
                    "toName": toName,
                    "message": data,
                    "code": 1
                };
                //将数据展示在聊天区
                var str = "<span class='message-sent'>" + data + "</span><br>";
                $("#content").append(str);

                // var chatData = JSON.parse(sessionStorage.getItem(toName)) || []; // 获取 chatData，如果不存在则为一个空数组
                //
                // chatData.push({ type: "text", data: str }); // 将 HTML 代码添加到 chatData 中
                //
                // sessionStorage.setItem(toName, JSON.stringify(chatData)); // 将 chatData 存储到 sessionStorag
                //发送数据
                ws.send(JSON.stringify(json));
            }

        })
        //发送图片
        $('#file').on('change', function () {
            var file = this.files[0];
            var fr = new FileReader();
            console.log("发送了一张图片");
            fr.onload = function (e) {
                var json = {
                    message: e.target.result,
                    toName: toName,
                    code: 2 // 2 表示图片消息
                };

                // 创建消息元素
                var messageDiv = $("<div>", { class: "message" });
                var img = document.createElement("img");
                img.src = e.target.result;
                messageDiv.append(img);
                messageDiv.addClass("img-sent"); // 添加 CSS 类
                //console.log(messageDiv);

                $("#content").append(messageDiv);
                // 添加到聊天记录
                // 更新聊天记录本地存储
                // var chatData = JSON.parse(sessionStorage.getItem(toName)) || [];
                // chatData.push({ type: "image", data: e.target.result });
                // sessionStorage.setItem(toName, JSON.stringify(chatData));
                //console.log(chatData);
                ws.send(JSON.stringify(json));
            };

            fr.readAsDataURL(file);
            document.getElementById("file").value = null;
        })
        $("#logout").click(function () {
            ws.close();
            $("#hylist").html("");
           // window.location.href = "login.html";
        })
       // 在页面关闭时保存 session 数据
        window.onbeforeunload = function () {
            ws.close();

        }

    })





    const chatBox = document.querySelector('.chat-box');
    const chatLog = document.querySelector('#content');
    const chatInput = document.querySelector('#input_text');
    const emojiButton = document.querySelector('#emoji-button');
    const emojiContainer = document.querySelector('#emoji-container');
    const emojiPicker = emojiContainer.querySelector('.emoji-picker');




    const emojis = [
        "😂",
        "😍",
        "😘",
        "😜",
        "😎",
        "💩",
        "🤔",
        "🙄",
        "🤭",
        "🤬",
        "🥳",
        "🤗",
        "😷",
        "🤢",
        "🤤",
        "🥺",
        "🤪",
        "🥴",
        "😴",
        "🤩",
        "🙌",
        "👏",
        "👀",
        "👌",
        "🙏",
        "🤝",
        "👊",
        "🤞",
        "👍",
        "👎",
        "🤟",
        "🤘",
        "👻",
        "👺",
        "💀",
        "👽",
        "🤖",
        "🤡",
        "👶",
        "👩‍",
        "🧔",
        "👨‍"
    ];


    emojis.forEach(function (emoji) {
        const button = document.createElement("button");
        button.className = "emoji";
        button.value = emoji;
        button.textContent = emoji;
        emojiPicker.appendChild(button);
    });

    emojiButton.addEventListener("click", function () {
        console.log("点了按钮");
        if (emojiContainer.style.display === "none") {
            emojiContainer.style.display = "block";
        } else {
            emojiContainer.style.display = "none";
        }
    });

    document.querySelectorAll(".emoji").forEach(function (item) {
        item.addEventListener("click", function () {
            const emoji = item.value;
            const start = chatInput.selectionStart;
            const end = chatInput.selectionEnd;
            const text = chatInput.value;
            const beforeText = text.substring(0, start);
            const afterText = text.substring(end);
            chatInput.value = beforeText + emoji + afterText;
            chatInput.selectionStart = chatInput.selectionEnd = start + emoji.length;
            chatInput.focus();
        });

    // 监听点击事件，如果点击到聊天框之外，隐藏表情选择器
    // 监听 body 上的点击事件
    document.body.addEventListener("click", function(event) {
        // 如果点击了 emojiButton 则不隐藏表情选择器
        if (event.target === emojiButton || emojiButton.contains(event.target)) {
            return;
        }

        // 如果点击了 emojiContainer 或 emojiContainer 子元素时不隐藏表情选择器
        if (emojiContainer.contains(event.target)) {
            return;
        }
        // 点击 emojiContainer 以外则隐藏表情选择器
        emojiContainer.style.display = "none";
    });

    })

</script>
</body>
</html>